package com.cloud.admin.controller;

import com.cloud.admin.common.constant.UserConstants;
import com.cloud.admin.common.core.domain.AjaxResult;
import com.cloud.admin.common.core.domain.Ztree;
import com.cloud.admin.model.entity.SysMenu;
import com.cloud.admin.model.entity.SysRole;
import com.cloud.admin.service.SysMenuService;
import com.cloud.admin.shiro.security.ShiroUtils;
import lombok.AllArgsConstructor;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import java.util.Date;
import java.util.List;

/**
 * Created on 2019/7/24.
 *
 * @author douhaichao
 */
@RestController
@AllArgsConstructor
@RequestMapping("system/menu")
public class MenuController extends BaseController {

    private final String prefix = "system/menu/";

    private final SysMenuService sysMenuService;

    @RequiresPermissions("system:menu:view")
    @GetMapping()
    public ModelAndView menu() {
        ModelAndView view = super.baseView("menue", prefix + "menu");
        return view;
    }

    @RequiresPermissions("system:menu:list")
    @PostMapping("list")
    public List<SysMenu> list(SysMenu menu) {
        Long userId = ShiroUtils.getUserId();
        List<SysMenu> menuList = sysMenuService.selectMenuList(menu, userId);
        return menuList;
    }

    /**
     * 删除菜单
     */
    @RequiresPermissions("system:menu:remove")
    @GetMapping("remove/{menuId}")
    public AjaxResult remove(@PathVariable("menuId") Integer menuId) {
        if (sysMenuService.selectCountMenuByParentId(menuId) > 0) {
            return AjaxResult.warn("存在子菜单,不允许删除");
        }
        if (sysMenuService.selectCountRoleMenuByMenuId(menuId) > 0) {
            return AjaxResult.warn("菜单已分配,不允许删除");
        }
        ShiroUtils.clearCachedAuthorizationInfo();
        return toAjax(sysMenuService.removeById(menuId));
    }

    /**
     * 新增
     */
    @GetMapping("add/{parentId}")
    public ModelAndView add(@PathVariable("parentId") Long parentId) {
        SysMenu menu = null;
        if (0L != parentId) {
            menu = sysMenuService.getById(parentId);
        } else {
            menu = new SysMenu();
            menu.setMenuId(0);
            menu.setMenuName("主目录");
        }
        ModelAndView view = super.baseView("menue", prefix + "add");
        view.addObject("menu", menu);
        return view;
    }

    /**
     * 新增保存菜单
     */
    @RequiresPermissions("system:menu:add")
    @PostMapping("add")
    public AjaxResult addSave(@Validated SysMenu menu) {
        if (UserConstants.MENU_NAME_NOT_UNIQUE.equals(sysMenuService.checkMenuNameUnique(menu))) {
            return error("新增菜单'" + menu.getMenuName() + "'失败，菜单名称已存在");
        }
        menu.setCreateBy(ShiroUtils.getLoginName());
        menu.setCreateTime(new Date());
        ShiroUtils.clearCachedAuthorizationInfo();
        return toAjax(sysMenuService.save(menu));
    }

    /**
     * 修改菜单
     */
    @GetMapping("edit/{menuId}")
    public ModelAndView edit(@PathVariable("menuId") Integer menuId) {
        ModelAndView view = super.baseView("menue", prefix + "edit");
        view.addObject("menu", sysMenuService.getMenueInfo(menuId));
        return view;
    }

    /**
     * 修改保存菜单
     */
    @RequiresPermissions("system:menu:edit")
    @PostMapping("edit")
    public AjaxResult editSave(@Validated SysMenu menu) {
        if (UserConstants.MENU_NAME_NOT_UNIQUE.equals(sysMenuService.checkMenuNameUnique(menu))) {
            return error("修改菜单'" + menu.getMenuName() + "'失败，菜单名称已存在");
        }
        menu.setUpdateBy(ShiroUtils.getLoginName());
        menu.setUpdateTime(new Date());
        ShiroUtils.clearCachedAuthorizationInfo();
        return toAjax(sysMenuService.updateById(menu));
    }

    /**
     * 选择菜单图标
     */
    @GetMapping("icon")
    public ModelAndView icon() {
        ModelAndView view = super.baseView("icon", prefix + "icon");
        return view;
    }

    /**
     * 校验菜单名称
     */
    @PostMapping("checkMenuNameUnique")
    @ResponseBody
    public String checkMenuNameUnique(SysMenu menu) {
        return sysMenuService.checkMenuNameUnique(menu);
    }

    /**
     * 加载角色菜单列表树
     */
    @GetMapping("roleMenuTreeData")
    public List<Ztree> roleMenuTreeData(SysRole role) {
        Long userId = ShiroUtils.getUserId();
        List<Ztree> ztrees = sysMenuService.roleMenuTreeData(role, userId);
        return ztrees;
    }

    /**
     * 加载所有菜单列表树
     */
    @GetMapping("menuTreeData")
    public List<Ztree> menuTreeData() {
        Long userId = ShiroUtils.getUserId();
        List<Ztree> ztrees = sysMenuService.menuTreeData(userId);
        return ztrees;
    }

    /**
     * 选择菜单树
     */
    @GetMapping("selectMenuTree/{menuId}")
    public ModelAndView selectMenuTree(@PathVariable("menuId") Integer menuId) {
        ModelAndView view = super.baseView("tree", prefix + "tree");
        view.addObject("menu", sysMenuService.getById(menuId));
        return view;
    }
}
